package com.fjh.security.easy.starter.config;

import es.moki.ratelimitj.core.limiter.request.RequestLimitRule;
import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter;
import es.moki.ratelimitj.inmemory.request.InMemorySlidingWindowRequestRateLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author fanjh37
 * @since 2023/2/11 12:14
 */
@Configuration
public class RequestRateLimiterConfig {

    @Autowired
    private EasyPropertiesConfig easyPropertiesConfig;

    @Bean
    @ConditionalOnMissingBean
    public RequestRateLimiter requestRateLimiter() {
        Set<RequestLimitRule> rules =
                Collections.singleton(RequestLimitRule.of(easyPropertiesConfig.getLock().getTimeOut(), TimeUnit.MINUTES, easyPropertiesConfig.getLock().getFailTime()));
        RequestRateLimiter limiter = new InMemorySlidingWindowRequestRateLimiter(rules);
        return limiter;
    }
}
